package com.huaxin.common.message;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.OpenClientUtil;

import java.net.URISyntaxException;
import java.util.List;

/**
 */
public class MapHelper2 {

    /**
     * 导航到地图应用
     *
     * @param id
     */
    public static void startNavi(int id, LatLng startPoint, String startName, LatLng endPoint, String endName, Context context) {
        if (id == 0) {
            startTencentNavi(context, startPoint, startName, endPoint, endName);
        } else if (id == 1) {
            startBaiduMapNavi(context, startPoint, startName, endPoint, endName);
        } else if (id == 2) {
            startGaoDeNavi(context, endPoint, endName);
        }
    }

    public static boolean isInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        final List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息
        if (pinfo != null) {
            for (PackageInfo info : pinfo) {
                if (info.packageName.equals(packageName)) {
                    return true;
                }
                //pName.add(pn);
            }
        }
        return false;
    }


    final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    /**
     * GCJ-02 坐标转换成 BD-09 坐标
     */
    public static double[] toBD09(double gg_lat, double gg_lon) {
        double x = gg_lon, y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double[] ret = new double[2];
        ret[1] = z * Math.cos(theta) + 0.0065;
        ret[0] = z * Math.sin(theta) + 0.006;
        return ret;
    }

    /**
     * BD-09 坐标转换成 GCJ-02 坐标
     */
    public static double[] fromBD09(double bd_lat, double bd_lon) {
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);

        double[] ret = new double[2];
        ret[1] = z * Math.cos(theta);
        ret[0] = z * Math.sin(theta);
        return ret;
    }

    /**
     * GCJ-02 坐标转换成 BD-09 坐标
     */
    public static LatLng toBD09(LatLng gg) {
        double x = gg.longitude, y = gg.latitude;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double[] ret = new double[2];
        ret[1] = z * Math.cos(theta) + 0.0065;
        ret[0] = z * Math.sin(theta) + 0.006;
        return new LatLng(ret[0], ret[1]);
    }

    /**
     * BD-09 坐标转换成 GCJ-02 坐标
     */
    public static LatLng fromBD09(LatLng bd) {
        double x = bd.longitude - 0.0065, y = bd.latitude - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);

        double[] ret = new double[2];
        ret[1] = z * Math.cos(theta);
        ret[0] = z * Math.sin(theta);
        return new LatLng(ret[0], ret[1]);
    }

    /**
     * 腾讯地图跳转URI
     */
    public static void startTencentNavi(Context context, LatLng startPoint, String startName, LatLng endPoint, String endName) {
        if (!isInstalled(context, "com.tencent.map")) {
            Toast.makeText(context, "请先下载安装腾讯地图客户端", Toast.LENGTH_SHORT).show();
            return;
        }
        startPoint = fromBD09(startPoint);//坐标转换
        endPoint = fromBD09(endPoint);//坐标转换
        /**
         * 	路线规划方式参数：
         公交：bus
         驾车：drive
         步行：walk（仅适用移动端）
         */
        StringBuffer stringBuffer = new StringBuffer("qqmap://map/routeplan?type=drive&from=")
                .append(startName)
                .append("&fromcoord=").append(startPoint.latitude).append(",").append(startPoint.longitude)
                .append("&to=").append(endName)
                .append("&tocoord=").append(endPoint.latitude).append(",").append(endPoint.longitude)
                .append("&policy=2")//0：较快捷1：无高速 2：距离
                .append("&referer=trydriver");
        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
        context.startActivity(intent);
    }

    /**
     * 高德地图跳转URI
     *
     * @param context
     * @param endPoint
     * @param endName
     */
    public static void startGaoDeNavi(final Context context, LatLng endPoint, String endName) {
        if (!isInstalled(context, "com.autonavi.minimap")) {
            Toast.makeText(context, "请先下载安装高德地图客户端", Toast.LENGTH_SHORT).show();
            return;
        }
        StringBuffer stringBuffer = new StringBuffer("androidamap://route?sourceApplication=").append("amap");
        endPoint = fromBD09(endPoint);//坐标转换

        stringBuffer.append("&dlat=").append(endPoint.latitude)
                .append("&dlon=").append(endPoint.longitude)
                .append("&dname=").append(endName)
                .append("&dev=").append(0) //起终点是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
                .append("&t=").append(0);  //t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）

        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
        intent.setPackage("com.autonavi.minimap");


        context.startActivity(intent);
    }

    /**
     * 百度地图跳转URI
     */
    public static void startBaiduMapNavi(final Context context, LatLng startPoint, String startName, LatLng endPoint, String endName) {
     //   Toast.makeText(context, "起始位置：" + startPoint.latitude + "  " + startPoint.longitude, Toast.LENGTH_LONG).show();
        try {
            String startLag = startPoint.latitude + "," + startPoint.longitude;
            String endLag = endPoint.latitude + "," + endPoint.longitude;
            /*导航模式，
            可选transit（公交）、
            driving（驾车）、
            walking（步行）和riding（骑行）.
            默认:driving*/
            Intent intent = Intent.getIntent("intent://map/direction?origin=latlng:" + startLag + "|name:" + startName + "&destination=latlng:" + endLag + "|name:" + endName + "&mode=driving&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");

            //Intent intent = Intent.getIntent("intent://map/direction?origin=|name:" + loc1.getAddress() + "&destination=|name:" + loc2.getAddress() + "&mode=transit&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");

            //起点  此处不传值默认选择当前位置
            // Intent intent = Intent.getIntent("intent://map/direction?destination=|name:" + loc2.getAddress() + "&mode=transit&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");
            context.startActivity(intent);

        } catch (URISyntaxException e) {
            e.printStackTrace();
            Toast.makeText(context, "地址解析错误", Toast.LENGTH_SHORT).show();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    OpenClientUtil.getLatestBaiduMapApp(context);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    }

}
